<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\OrderTemporary;
use app\common\model\Product as ProductModel;
use app\common\model\ProductCate;
use app\common\model\ProductSpec;
use app\common\tool\Result;
use think\facade\Cache;
use think\Response;

class Product extends Base
{

    /**
     * 商品详情
     */
    public function details()
    {
        $param = $this->request->get();
        try {
            $info = ProductModel::where(['status' => 1, 'id' => $param['id']])->find();
            if (empty($info)) return Result::fail('商品不存在！');
            $info->images = explode(',', $info->images);
            $info->sales = $info->sales + $info->virtual_sales;
            $url = 'http://' . $_SERVER['SERVER_NAME'] . '/uploads/';
            $info->content = htmlspecialchars_decode(str_replace('/uploads/', $url, $info->content));
            $info->content = str_replace('\\', '', $info->content);
            return Result::success('获取成功！', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 商品列表
     */
    public function getList(): Response
    {
        $param = $this->request->get();
        try {
            $map[] = ['status', '=', 1];
            $map[] = ['cate_1', '=', $param['cate_1']];
            $list = ProductModel::getPageList($map, 'id,title,price,vip_price,icon', $param['page'], 20, true, '', '', ['key' => 'sort', 'value' => 'asc'],);
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 购买提交
     */
    public function submit(): Response
    {
        $param = $this->request->post();
        try {
            $param['type'] = 1;
            return Result::fastReturn(OrderTemporary::setTemporary($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
